package com.jialea.luobochat.server.controller;

import com.jialea.luobochat.common.exception.BusinessException;
import com.jialea.luobochat.common.result.Result;
import com.jialea.luobochat.common.utils.file.FileTypeUtils;
import com.jialea.luobochat.server.service.MinIOService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * 文件处理控制器
 *
 * @author: wjl
 * @date: 2024/10/19 19:03
 */
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private MinIOService minIOService;

    /**
     * 图片上传
     *
     * @param file
     * @return
     */
    @PostMapping("/uploadImage")
    public Result<String> uploadImage(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new BusinessException("图片为空");
        }
        //获取原始图片名称
        String originalFilename = file.getOriginalFilename();
        //获取文件后缀
        String suffix = FileTypeUtils.getFileTypeIncludePoints(originalFilename);
        //新的文件名称
        String newFileName = new StringBuffer().append(UUID.randomUUID()).append(suffix).toString();
        //返回图片路径
        String fileName = minIOService.uploadImgFile(newFileName, file.getContentType(), file.getInputStream());
        return Result.success(fileName);
    }
}
